<template>
  <div class="app-container">
    <el-card shadow="never">
      <div class="flex-x-between mb-10px">
        <div>
          <el-button v-hasPerm="['/admin/water/chargeRule/add']" type="success" icon="plus" @click="handleOpenDialog()">
            新增
          </el-button>
          <el-button :disabled="selectIds.length === 0" v-hasPerm="'/admin/water/chargeRule/del'" type="danger"
            icon="delete" @click="handleDelete()">
            删除
          </el-button>
        </div>
      </div>
      <el-table ref="dataTableRef" v-loading="loading" :data="pageData" highlight-current-row
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="规则id" prop="id" width="80" />
        <el-table-column label="规则名称" prop="name" width="140" />
        <el-table-column label="收水规则" prop="balance" min-width="140">
          <template #default="scope">
            <span>{{ scope.row?.charge_mode == 1 ? '统一定价' : '阶梯收费' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最终收费价格" prop="final_price" width="200">
          <template #default="scope">
            <span>{{ scope.row?.charge_mode == 1 ? scope.row?.final_price : "/" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="城市供水运营水费" prop="urban_price" width="200">
          <template #default="scope">
            <span>{{ scope.row?.charge_mode == 1 ? scope.row?.urban_price : "/" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="水利工程运营水费" prop="conservancy_price" width="200">
          <template #default="scope">
            <span>{{ scope.row?.charge_mode == 1 ? scope.row?.conservancy_price : "/" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="水资源费" prop="resource_price" width="140">
          <template #default="scope">
            <span>{{ scope.row?.charge_mode == 1 ? scope.row?.resource_price : "/" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="污水处理费" prop="sewage_treat_price" width="140">
          <template #default="scope">
            <span>{{ scope.row?.charge_mode == 1 ? scope.row?.sewage_treat_price : "/" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="created_at" width="180">
          <template #default="scope">
            {{ formatTimestamp(scope.row.created_at * 1000) }}
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="200">
          <template #default="scope">
            <el-button v-hasPerm="'/admin/water/chargeRule/detail'" type="primary" size="small" link icon="Document"
              @click="handleOpenDialog(scope.row, 'info')">
              详情
            </el-button>
            <el-button v-hasPerm="'/admin/water/chargeRule/update'" type="primary" size="small" link icon="edit"
              @click="handleOpenDialog(scope.row, 'edit')">
              修改
            </el-button>
            <el-button v-hasPerm="'/admin/water/chargeRule/del'" type="danger" icon="delete" link size="small"
              @click="handleDelete(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.page" v-model:limit="queryParams.ps"
        @pagination="handleQuery()" />
    </el-card>

    <!-- 片区表单 -->
    <el-dialog :close-on-click-modal="false" v-model="dialog.visible" width="60%" :title="dialog.title" append-to-body
      @close="handleCloseDialog">
      <el-form ref="formRef" :disabled="infoType" :model="formData" :rules="rules" label-width="140px">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="规则模式" prop="charge_mode" placeholder="规则模式">
          <el-radio-group v-model="formData.charge_mode" @change="hanldeChangeRadio">
            <el-radio value="1" label="统一定价" />
            <el-radio value="2" label="梯度收费" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="formData.desc" placeholder="请输入描述" />
        </el-form-item>
        <template v-if="formData.charge_mode == 1">
          <el-form-item label="城市供水运营水费" prop="urban_price">
            <el-input @input="hanldePrice" v-model="formData.urban_price" placeholder="请输入城市供水运营水费" />
          </el-form-item>
          <el-form-item label="水利工程运营水费" prop="conservancy_price">
            <el-input @input="hanldePrice" v-model="formData.conservancy_price" placeholder="请输入水利工程运营水费" />
          </el-form-item>
          <el-form-item label="水资源费" prop="resource_price">
            <el-input @input="hanldePrice" v-model="formData.resource_price" placeholder="请输入水资源费" />
          </el-form-item>
          <el-form-item label="污水处理费" prop="sewage_treat_price">
            <el-input @input="hanldePrice" v-model="formData.sewage_treat_price" placeholder="请输入污水处理费" />
          </el-form-item>
          <el-form-item label="最终价格" prop="final_price">
            <el-input disabled v-model="formData.final_price" placeholder="请输入最终价格" />
          </el-form-item>
        </template>
        <template v-if="formData.charge_mode == 2">
          <el-form-item :label="`第(${index + 1})阶段`" v-for="(item, index) in formData.stage_charge" :key="item.id">
            <div style="width: 100%;">
              <el-row :gutter="20">
                <el-col :span="12" class="mb-2">
                  <el-form-item label="阶梯名称">
                    <el-input v-model="item.name" placeholder="请输入阶梯名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-2">
                  <el-form-item label="用水量">
                    <div class="flex">
                      <el-input v-model="item.min" placeholder="最小" />
                      <div class="mr-2 ml-2">-</div>
                      <el-input v-model="item.max" placeholder="最大" />
                    </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-2">
                  <el-form-item label="城市供水运营水费">
                    <el-input @input="hanldePriceArr(index)" v-model="item.urban_price" placeholder="请输入城市供水运营水费" />
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-2">
                  <el-form-item label="水利工程运营水费">
                    <el-input @input="hanldePriceArr(index)" v-model="item.conservancy_price"
                      placeholder="请输入水利工程运营水费" />
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-2">
                  <el-form-item label="水资源费">
                    <el-input @input="hanldePriceArr(index)" v-model="item.resource_price" placeholder="请输入水资源费" />
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-2">
                  <el-form-item label="污水处理费">
                    <el-input @input="hanldePriceArr(index)" v-model="item.sewage_treat_price" placeholder="请输入污水处理费" />
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-2">
                  <el-form-item label="最终价格">
                    <el-input disabled v-model="item.final_price" placeholder="请输入最终价格" />
                  </el-form-item>
                </el-col>
                <el-col :span="12" class="mb-2 text-right">
                  <el-button @click="hanldeDelChoice(index)" v-if="index > 1 && !infoType"
                    type="danger">删除选项</el-button>
                </el-col>
              </el-row>
            </div>
          </el-form-item>
          <el-form-item v-if="!infoType">
            <div class="flex">
              <el-button type="primary" @click="addChoiceList">新增选项</el-button>
              <span>（最多添加10个选项）</span>
            </div>
          </el-form-item>
        </template>
      </el-form>

      <template #footer>
        <div class="dialog-footer" v-if="!infoType">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ChargeRule",
  inheritAttrs: false,
});

import chargeRuleAPI, { Form, PageVO, chargeRulePageQuery } from "@/api/waterMeter/chargeRule";
import { formatTimestamp } from '@/utils/index';

const pageData = ref<PageVO[]>([]);
const formRef = ref(ElForm);
const loading = ref(false);
const total = ref(0);

const queryParams = reactive<chargeRulePageQuery>({
  page: 1,
  ps: 10,
});

const dialog = reactive({
  visible: false,
  title: "新增规则",
});

// 默认值
const hanldeChangeRadio = (val: any) => {
  if (formData.charge_mode == 1) {
    formData.stage_charge = [];
  } else if (formData.charge_mode == 2) {
    formData.stage_charge = [
      { name: '', urban_price: '', conservancy_price: '', resource_price: '', sewage_treat_price: '' },
      { name: '', urban_price: '', conservancy_price: '', resource_price: '', sewage_treat_price: '' }
    ]
  }
}

// 选中的ID
const selectIds = ref<number[]>([]);

const formData = reactive<Form>({
  name: "",
  charge_mode: "1",
  urban_price: "",
  conservancy_price: "",
  resource_price: "",
  final_price: "",
  sewage_treat_price: "",
  desc: "",
  stage_charge: []
});

const rules = reactive({
  name: [{ required: true, message: "规则名称", trigger: "blur" }],
  desc: [{ required: true, message: "请输入描述", trigger: "blur" }],
  urban_price: [{ required: true, message: "请输入运营水费", trigger: "blur" }],
  conservancy_price: [{ required: true, message: "请输入水利工程运营水费", trigger: "blur" }],
  resource_price: [{ required: true, message: "请输入水资源费", trigger: "blur" }],
  sewage_treat_price: [{ required: true, message: "请输入污水处理费", trigger: "blur" }],
});

/**
 * 打开弹窗
 *
 * @param id 片区ID
 */
const infoType = ref(false);
async function handleOpenDialog(data?: any, type?: any) {
  dialog.visible = true;
  if (data) {
    if (type == 'info') {
      infoType.value = true;
      dialog.title = "详情";
    } else {
      infoType.value = false;
      dialog.title = "修改规则";
    }
    chargeRuleAPI.detail(data.id).then((res: any) => {
      res.info.charge_mode = res.info.charge_mode + '';
      Object.assign(formData, { ...res.info });
    })
  } else {
    infoType.value = false;
    dialog.title = "新增规则";
  }
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  formRef.value.resetFields();
  formRef.value.clearValidate();

  formData.id = undefined;
}

// 新增选项
const addChoiceList = () => {
  if (formData.stage_charge.length >= 10) {
    ElMessage.warning('选项不能超过10个');
    return;
  }
  formData.stage_charge.push(
    {
      name: '',
      urban_price: '',
      conservancy_price: '',
      resource_price: '',
      sewage_treat_price: '',
      min: '',
      max: ''
    }
  );
}

// 删除选项
const hanldeDelChoice = (index: number) => {
  formData.stage_charge.splice(index, 1);
}

// 计算金额
const hanldePrice = () => {
  formData.final_price = (Number(formData.conservancy_price) + Number(formData.resource_price) + Number(formData.sewage_treat_price) + Number(formData.urban_price)).toFixed(2);
}
// all 计算金额
const hanldePriceArr = (i: any) => {
  let item = formData.stage_charge[i]
  item.final_price = (Number(item.conservancy_price) + Number(item.resource_price) + Number(item.sewage_treat_price) + Number(item.urban_price)).toFixed(2);
}

// 提交表单（防抖）
const handleSubmit = useDebounceFn(() => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      loading.value = true;
      if (formData.id) {
        chargeRuleAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        chargeRuleAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 1000);

// 选中项发生变化
function handleSelectionChange(selection: any[]) {
  selectIds.value = selection.map((item) => item.id);
}

/**
 * 删除片区
 *
 * @param id  片区ID
 */
function handleDelete(id?: number) {
  let delIds = id ? [id] : selectIds.value;
  if (!delIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除规则?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    function () {
      loading.value = true;
      chargeRuleAPI.deleteByIds({ ids: delIds })
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    function () {
      ElMessage.info("已取消删除");
    }
  );
}

/** 查询通知公告 */
function handleQuery() {
  loading.value = true;
  chargeRuleAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置通知公告查询 */
function handleResetQuery() {
  formRef.value!.resetFields();
  queryParams.page = 1;
  handleQuery();
}

onMounted(() => {
  handleQuery();
});
</script>
